"""

Very much in progress... doesn't actually do anything yet.




Where some files go.

lib/cherrypy
lib/SQLAlchemy
lib/db.py
lib/...

db/database_dump.sql

www/skins/...

www/shots/
"""

import sys, random, time, user, pickle, os, math
from pprint import pprint

libdir = os.path.abspath(os.path.join(os.path.dirname(__file__), 'lib'))
sys.path.insert(0, libdir)


import cherrypy
from cherrypy.lib.static import serve_file


from pygame.locals import *
import pygame


import game

WIDTH = 640
HEIGHT = 480

WEB = pygame.USEREVENT+3

class Web(game.Game):





    def start(self, object_scriptname_config, port):
        """ starts a http server.
        """
        # so if we are changing our code whilst running a test, it doesn't stuff up the test.
        cherrypy.config.update({"engine.autoreload_on" : False})

        cherrypy.config.update({"server.socket_port" : int(port),
                                "server.socket_host": "0.0.0.0"
                                })

        for root, script_name, config in object_scriptname_config:
            cherrypy.tree.mount(root, script_name, config = config)

        #cherrypy.server.quickstart()

        cherrypy.engine.start()


    def stop_server(self):
        """
        """
        #cherrypy.tree.apps = {}
        
        
        #import pdb;pdb.set_trace()
        cherrypy.engine.exit()
        cherrypy.server.stop()
        



    def index(self):
        return "lalala"
    index.exposed = True

    def example_post(self, *args, **kwargs):
        """ for example, if you wanted to post a url into a pygame event,
            you could do it something like this...
        """
        e = pygame.event.Event(WEB, args = args, kwargs = kwargs )
        pygame.fastevent.post(e)

    def project(self, id = None, release = None):
        """ show the projects.
        """

    def news(self):
        """ show the latest news.
        """

    def wiki(self, page = None, parent = None):
        """ show wiki pages.
            page - 
            parent - 
        """








    def load(self):
        """
        """
        game.Game.load(self)


        # Initialise some state.
        self.elapsed_time = 0.
        
        # should we be blitting the image to the screen.
        self.blit = True
        
        # Do we have a display?
        self.display = True




    def stop(self):
        """ stops various things...
        """
        
            
        



    def handle_events(self, events):
        """

        >>> Event = pygame.event.Event


        >>> events = []
        >>> w = Web()
        >>> w.handle_events(events)

        Does a quit event stop it?

        >>> events = [Event(QUIT)]

        >>> w = Web()
        >>> w.going
        True

        >>> w.handle_events(events)
        >>> w.going
        False


        """

        game.Game.handle_events(self, events)
        

        for e in events:
            if e.type in [QUIT]:
                self.going = False
            elif e.type == KEYDOWN:
                if e.key == K_ESCAPE:
                    self.going = False

                if e.key == K_s:
                    print 's!'



    def update(self, elapsed_time):
        """
        """
        game.Game.update(self, elapsed_time)








def main():
    class Constants:pass
    constants = Constants()
    constants.fps = 30
    constants.screen_size = (WIDTH, HEIGHT)

    startup0 = time.time()

    # turn off logging to the screen with cherrypy.
    #cherrypy.config.update({"log.screen" : False})


    top = Web(name = "pygame.org")
    #top.set_main()




    listen_port = 9942




    # serve up the images.
    top.root_dir = os.path.dirname(os.path.abspath(__file__))


    #some_conf = {"/" : {'tools.staticdir.root': os.path.join(top.root_dir),
    #                   },
    #             '/bla' : {'tools.staticdir.on': True,
    #                       'tools.staticdir.dir': 'bla'}
    #            }
    some_conf = {}








    #pygame.font.init()
    #pygame.threads.init(8)


    screen = pygame.display.set_mode((WIDTH, HEIGHT))
    pygame.fastevent.init()
    pygame.key.set_repeat (500, 30)




    if listen_port:
        # start up the cherrypy webserver.
        top.start([[top, "/", some_conf]], int(listen_port))

        pygame.display.set_caption("is it a website or a game? port:%s:" % (listen_port))
        pygame.fastevent.get()







    try:

        # a main loop.

        clock = pygame.time.Clock()
        clock.tick()

        while top.going:
            elapsed_time = clock.get_time()
            if elapsed_time:
                elapsed_time = elapsed_time / 1000.


            # speed up time...
            #elapsed_time *= 4

            if top.display:
                #events = pygame.fastevent.get()
                events = [pygame.fastevent.wait()] + pygame.fastevent.get()

                # we pass in the events so all of them can get the events.
                top.handle_events(events)


            # each part that uses time, for animation or otherwise
            #   gets the same amount of elapsed time.  This also reduces the
            #   number of system calls (gettimeofday) to one per frame.
            #top.update(elapsed_time)
            top.update(elapsed_time)



            if top.blit:
                # the draw method retunrns a list of rects,
                #   for where the screen needs to be updated.
                rects = top.draw(screen)

                # remove empty rects.
                rects = filter(lambda x: x != [], rects)
                #rects = filter(lambda x: type(x) not in map(type, [pygame.Rect, [], tuple([1,2])]) , rects)
                rects = filter(lambda x: type(x) not in map(type, [1]) , rects)


                # if not empty, then update the display.
                if rects != []:
                    #print rects
                    pygame.display.update(rects)
                #pygame.display.update(rects)

            # we ask the clock to try and stay at a FPS rate( eg 30fps).
            #  It won't get exactly this, but it tries to get close.
            #clock.tick(constants.fps)
            clock.tick()
            #print clock.get_fps()

    except:
        raise

    finally:
        #print 'stopping-----------------------'
        top.stop()
        top.stop_server()



def _test():
    import doctest
    doctest.testmod()
    #doctest.run_docstring_examples(somefunc, globals())



if __name__ == "__main__":
    main()
    #_test()



